const path = require('path')
const fs = require('fs')
const glob = require('glob')

class Store {

    constructor (config) {
        this.config = config
        fs.watch(path.resolve(config.root, config.path, config.modules), (type, filename) => {
            this.build()
        })
    }

    build () {
        const root = path.resolve(this.config.root, this.config.path, this.config.modules)
        const files = glob.sync(path.resolve(root, '**', '*.js'))
        let data = '/* eslint-disable */\r\nexport default {\r\n'
        let n = 0
        files.map(file => {
            let str = new RegExp((root + path.sep + '(.+?)\.js').replace(/\\/g, '/'))
            file = file.match(str)
            if (!file) {
                return
            }
            str = file[1]
            data += `   '${str}': require('./${this.config.modules}/${str}.js').default,\r\n`
            n ++
        })
        data += '}'
        fs.writeFile(path.resolve(this.config.root, this.config.path, this.config.table) + '.js', data, (err) => {
            if (err) {
                throw err
            }
            console.info("\r\n\r\n=================================\r\n")
            console.log(err)
            console.info('store.table build success!')
            console.info("\r\n=================================\r\n\r\n")
        })
    }
}



class WebpackAotoBuildStorePlugin {
    constructor (config) {
        if (!config) {
            throw 'config不允许为空'
        }
        if (!config.path) {
            throw 'config.path不允许为空'
        }
        if (!config.table) {
            throw 'config.table不允许为空'
        }
        if (!config.modules) {
            throw 'config.modules不允许为空'
        }
        this.config = config
    }


    apply (compiler) {
        compiler.hooks.entryOption.tap('WebpackAotoBuildStorePlugin', (context, entry) => {
            this.config.root = context
            const store = new Store(this.config)
            store.build()
        })
    }
}

module.exports = WebpackAotoBuildStorePlugin
